package com.qingcheng.consumer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.StockBackService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.pay.WeixinPayService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;
import java.util.Map;

/**
 * Created by yuanxin
 * Date:2019/7/18
 * Time:18:54
 */
public class TimeOutMessageConsumer implements MessageListener {
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private OrderService orderService;

    @Override
    public void onMessage(Message message) {
        String jsonString = new String(message.getBody());
        String orderId = JSON.parseObject(jsonString, String.class);
        Order order = orderService.findById(orderId);
        if (order != null) {
            if ("0".equals(order.getPayStatus()) && "0".equals(order.getOrderStatus())) {
                Map queryMap = weixinPayService.queryPaymentResultByOrderId(orderId);
                if ("NOTPAY".equals(queryMap.get("trade_state"))) {//未支付
                    orderService.closeOrderByOrderId(orderId);
                }else if("SUCCESS".equals(queryMap.get("trade_state"))) {//支付成功
                    orderService.updatePayStatus(orderId,(String) queryMap.get("transaction_id"));
                }else {
                    throw new RuntimeException("其他支付状态,没判断");
                }
            }else {
                throw new RuntimeException("订单已支付,无法关闭,请走退款");
            }

        }else {
            throw new RuntimeException("没有对应订单");
        }
    }
}
